import { Component, EventEmitter, OnInit, Output } from "@angular/core";
import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { SysMenuService } from "../sys-menu.service";
import { NzMessageService } from "ng-zorro-antd/message";


@Component({
  selector: "menu-list-edit",
  templateUrl: "./menu-edit.component.html"
})
export class MenuEditComponent implements OnInit {

  @Output() voted = new EventEmitter();

  validateForm!: FormGroup;
  visible = false;
  value?: string;
  nodes = [];

  open(): void {
    this.visible = true;

  }

  edit(param) {
    this.visible = true;
    this.value = param?.parent?.id;

    if (param) {
      this.validateForm.patchValue(param);
    } else {
      this.validateForm.reset();
    }

    this.menService.menuTree().subscribe((res) => {
      this.nodes = res.data;
    });
  }

  close(): void {
    this.visible = false;
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (this.validateForm.invalid) {
      return;
    }

    this.menService.save(this.validateForm.value).subscribe((res) => {
      if (res.code === 1) {
        this.msgSrv.success("保存完成");
        this.close();
        this.voted.emit();
      } else {
        this.msgSrv.error(res.message);
      }
    });
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  };

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }

  constructor(private fb: FormBuilder,
              private menService: SysMenuService,
              private msgSrv: NzMessageService) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      id: [null],
      parentId: [null],
      menuCode: [null, [Validators.required]],
      menuName: [null, [Validators.required]],
      icon: [null],
      url: [null],
      idx: [null, [Validators.required]]
    });
  }


  onChange($event: string): void {
    console.log($event);
  }

}
